<template>
  <view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
    <view class="content detail">
    	<!-- 轮播图 -->
    	<uni-swiper-dot class="uni-swiper-dot-box" :info="navigation" :current="current" field="content">
    	  <swiper  class="swiper-box" :current="swiperDotIndex" @change="changeSwiper">
    	    <swiper-item v-for="(item, index) in navigation" :key="index">
    	      <view class="swiper-item" @click="clickBannerItem(item)">
    	        <image :src="item.img" mode="aspectFill" :draggable="false" />
    	      </view>
    	    </swiper-item>
    	  </swiper>
    	</uni-swiper-dot>
			
			<!--今日打卡-->
			<view class="detail-item" v-if="checkPermi(['zhouyz:salesmanPath:add']) && !checkRole(['admin'])">
				<uni-section title="今日打卡" type="line"></uni-section>
				<view class="detail-content location">
					<view class="location-loading main-flex" @click="clock">
						<view class="location-loading-icon" v-if="isLocationLoading"></view>
						<text class="location-loading-text" v-if="isLocationLoading">定位中</text>
						<view class="location-loading-clock main-flex" v-else>位置打卡</view>
					</view>
					<view class="location-info" v-if="!isLocationLoading && address">
						<view class="">地点：{{address}}</view>
						<view class="">时间：{{time}}</view>
						<view @click="showMap" v-if="setStore.baseUrl === 'https://erp.zyzy.team' && userStore?.user?.userName === 'caiw'">经度：{{location.longitude}}；纬度：{{location.latitude}}</view>
					</view>
				</view>
			</view>
			<!--常用菜单-->
			<view class="detail-item">
				<uni-section title="常用菜单" type="line"></uni-section>
				<view class="grid-body">
					<view class="grid-list main-flex" :showBorder="false">
						<block v-for="itemChild in menu" :key="itemChild.name" >
						<view style="width: 25%;" @click="changeGrid(itemChild)" v-if="!itemChild.hidden">
							<view class="grid-item-box">
								<image class="grid-item-icon" mode="aspectFit" :src="itemChild?.meta?.icon && itemChild.meta.icon !== '#' ? `/static/images/icon/svg/${itemChild.meta.icon}.svg` : ''"></image>
								<text class="text">{{itemChild.meta.title}}</text>
							</view>
						</view>
						</block>
					</view>
				</view>
			</view>
			<!--积分薪资-->
			<view class="detail-item main-flex" v-if="userStore?.userSalesman" style="align-items: flex-start;">
				<view class="main-flex-item">
					<uni-section title="累计积分" type="line"></uni-section>
					<view class="jf main-flex">
						<image class="jf-icon" src="/static/images/jf.png"></image>
						<up-count-to color="#2fc25b" fontSize="36" bold :startVal="0" :endVal="userStore?.userSalesman?.integral"></up-count-to>
					</view>
				</view>
				<view class="main-flex-item" v-if="userStore?.userKpiPosts && userStore.userKpiPosts.length > 0">
					<uni-section title="预计薪资(基本工资+绩效)" type="line"></uni-section>
					<view class="jf main-flex">
						<image class="jf-icon" src="/static/images/xz.png"></image>
						<up-count-to color="#f04864" fontSize="36" bold :startVal="0" :endVal="salaryMoney"></up-count-to>
					</view>
				</view>
			</view>
			<!--本月KPI-->
			<view class="detail-item">
				<uni-section v-if="$u.test.digits(userStore?.user?.remark)" title="累计积分" type="line"></uni-section>
				<view class="jf main-flex" v-if="$u.test.digits(userStore?.user?.remark)">
					<up-count-to color="#2fc25b" fontSize="36" bold :startVal="0" :endVal="userStore.user.remark"></up-count-to>
				</view>
				<uni-section title="本月KPI达成率" type="line"></uni-section>
				<view class="detail-content qiun">
					<qiun-data-charts class="qiun-item" type="gauge" :opts="gaugeOpts" :chartData="chartData" />
				</view>
				<uni-section title="本月指标完成信息" type="line"></uni-section>
				<view class="detail-content qiun main-flex">
					<ty-table
						:data="kpiList"
						:columns="kpiColumns"
						:sortable="true"
						:cellClassName="() => 'table-cell'"
						:headerCellClassName="() => 'table-cell'"
						stripe
						border>
						<template v-slot:proportion="{row}">
							{{Math.floor(row.proportion * 100)}}%
						</template>
						<template v-slot:percentage="{row}">
							<text class="percentage">{{row.percentage}}%</text>
						</template>
						<template v-slot:completionValue="{row}">
							<text class="percentage">{{row.completionValue}}</text>
						</template>
						<template v-slot:empty>
							<view class="table-empty">
								<up-empty mode="data"/>
							</view>
						</template>
					</ty-table>
				</view>
			</view>
    	
    </view>
		
		
		<!-- 打卡框 -->
		<up-modal
			:show="showLocation"
			@confirm="confirmLocation"
			@cancel="closeLocation"
			@close="closeLocation"
			showCancelButton
			title="确认打卡" >
			<view class="slot-location">
				<view class="">地点：{{address}}</view>
				<view class="">时间：{{time}}</view>
			</view>
		</up-modal>
  </view>
</template>

<script setup>
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set.js'
import { tab, auth, modal } from "@/plugins"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import { ref, onMounted, watch, computed} from 'vue'
import { kpiPostSchedule } from "@/api/erp_api/kpi"
import { getUserProfile } from "@/api/system/user"
import { timeFormat, throttle } from 'uview-plus'
import { Decimal } from 'decimal.js'
import { getUserLocation, conversion, previewImg } from '@/utils/ty.js'
import { salesmanPathAdd } from "@/api/erp_api/sale"
import qiunDataCharts from '@/components/qiun-data-charts/qiun-data-charts.vue'
import { onShow, onReady } from '@dcloudio/uni-app'
import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update'
import { onPullDownRefresh } from '@dcloudio/uni-app'

	const userStore = useUserStore()
	const setStore = useSetStore()
	const gaugeOpts = ref({
		fontSize: 10,
		width: 150,
		height: 150,
		color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
		padding: undefined,
		title: {
			name: "达成率",
			fontSize: 16,
			color: "#666666",
			offsetY: 40
		},
		subtitle: {
			name: "%",
			fontSize: 16,
			color: "#2fc25b",
			offsetY: -40
		},
		extra: {
			gauge: {
				type: "default",
				width: 16,
				labelColor: "#666666",
				startAngle: 0.75,
				endAngle: 0.25,
				startNumber: 0,
				endNumber: 100,
				labelFormat: "",
				splitLine: {
					fixRadius: 0,
					splitNumber: 10,
					width: 10,
					color: "#FFFFFF",
					childNumber: 5,
					childWidth: 6
				},
				pointer: {
					width: 24,
					color: "auto"
				}
			}
		}
	})
	
	const categories = [
		{"value":0.2,"color":"#f04864"} ,
		{"value":0.8,"color":"#2fc25b"} ,
		{"value":1,"color":"#1890ff"},
	]
	
	const chartData = ref({
		categories: categories,
		series: [
			{
				name: "KPI总完成率",
				data: 0
			}
		]
	})
	const kpiPercentage = ref(0)
	const kpiColumns = ref([
		{ title: '名称', key: 'targetName', align: 'center' },
		{ title: '占比', key: 'proportion', width: '120rpx', align: 'center' },
		{ title: '指标', key: 'targetValue', width: '120rpx', align: 'center' },
		{ title: '完成', key: 'completionValue', width: '120rpx', align: 'center' },
		{ title: '完成率', key: 'percentage', width: '120rpx', align: 'center' }
	])
	const kpiList = ref([])
	const getKpiPostSchedule = () => {
		kpiPostSchedule({
			targetMonth: timeFormat(new Date(), 'ym'),
			completionUser: userStore.user.userId
		}).then(res => {
			kpiList.value = res.rows.map(item => {
				const percentage = Decimal(item.completionValue).div(Decimal(item.targetValue)).toNumber()
				return {
					...item,
					percentage: percentage > 1 ? 100 : Math.floor(percentage * 10000) / 100
				}
			})
			const kpiAll = res.rows.reduce((prev, cur, index, arr)=> {
				const kpi = Decimal(cur.completionValue).div(Decimal(cur.targetValue)).toNumber()
				const kpiOne = kpi > 1 ? Decimal(cur.proportion) : Decimal(kpi).mul(Decimal(cur.proportion))
				return Decimal(prev).add(kpiOne).toNumber()
			}, 0)
			
			const kpiJson = {
				categories: categories,
				series: [
					{
						name: "KPI总完成率",
						data: kpiAll
					}
				]
			}
			kpiPercentage.value = Math.floor(kpiAll * 10000) / 100
			gaugeOpts.value.subtitle.name = `${kpiPercentage.value}%`
			chartData.value = JSON.parse(JSON.stringify(kpiJson))
		})
	}
	
	// 打卡
	
	const isLocationLoading = ref(false)
	const address = ref('')
	const time = ref('')
	const location = ref(null)
	// 获取当前位置
	const getLocation = () => {
		isLocationLoading.value = true
		getUserLocation().then(res => {
			isLocationLoading.value = false
			location.value = {
				latitude: res.latitude,
				longitude: res.longitude
			}
			address.value = res.formatted_address
			time.value = timeFormat('', 'yyyy-mm-dd h:M:s')
		}).catch(err => {
			modal.showToast(err)
		})
	}
	const showLocation = ref(false)
	// 点击打卡
	const clock = () => {
		if (isLocationLoading.value) return false
		time.value = timeFormat('', 'yyyy-mm-dd h:M:s')
		showLocation.value = true
	}
	
	// 关闭弹窗
	const closeLocation = () => {
		showLocation.value = false
	}
	// 确认打卡
	const isLocation = ref(false)
	const confirmLocation = async () => {
		if (isLocation.value) return false
		if (!location.value || !location.value.latitude) return modal.showToast('经纬度不存在')
		const point = await conversion(location.value.longitude, location.value.latitude)
		if (point.latitude && point.latitude !== '0') {
			isLocation.value = true
			salesmanPathAdd({
				lat: point.latitude,
				lng: point.longitude,
				recordTime: time.value,
				userId: userStore.user.userId,
				remark: '打卡'
			}).then(res => {
				modal.showToast('打卡成功')
				isLocation.value = false
				closeLocation()
			}).catch((err) => {
				modal.showToast(err)
				isLocation.value = false
			})
		}
	}
	
	onShow(() => {
		if (checkPermi(['zhouyz:salesmanPath:add']) && !checkRole(['admin'])) {
			getLocation()
		}
		if (checkPermi(['zhouyz:kpiPostSchedule:list'])) {
			getKpiPostSchedule()
		}
	})
	
	const current=ref(0);
	const swiperDotIndex=ref(0);
	
	function clickBannerItem(item) {
	  // console.info(item)
		if (item.url) {
			uni.navigateTo({
				url: item.url
			})
		} else {
			previewImg(item.img, navigation.value.map(item => item.img))
		}
	};
	function changeSwiper(e) {
	  current.value = e.detail.current
	}
	// 获取菜单
	const menu = ref([])
	watch(() => userStore.menu, (newVal, oldVal) => {
		menuTools(newVal)
	})
	
	onShow(() => {
		uni.setTabBarStyle({
			backgroundColor: setStore.env === 'test' ? '#2c9af1' : '#ffffff'
		})
		if (userStore.menu) {
			menuTools(userStore.menu)
		}
	})
	// 菜单处理
	const menuTools = (newVal = userStore.menu) => {
		let menuList = []
		menu.value = []
		const menuClick = setStore.menuClicks
		for(let i = 0; i < newVal.length; i++) {
			if (newVal[i].children) {
				newVal[i].children = newVal[i].children.map(item => {
					const filterMenuClick = menuClick.filter(itemMenu => itemMenu.p1 === newVal[i].name && itemMenu.p2 === item.name)
					return {
						...item,
						parent: newVal[i], 
						c: filterMenuClick.length > 0 ? filterMenuClick[0].c : 0,
						url: `/pages/${newVal[i].path.replace(/^\//, '')}/${item.path.replace(/^\//, '')}`
					}
				})
				menuList = [...menuList, ...newVal[i].children]
			}
		}
		menu.value = menuList.sort((a, b) => b.c - a.c).filter(item => !item.hidden).slice(0, 4)
	}
	
	const navigation = ref(userStore.navigation)
	watch(() => userStore.navigation, (newVal, oldVal) => {
		navigation.value = newVal
	})
	watch(() => userStore.user.userId, (newVal, oldVal) => {
	})
	
	function changeGrid(itemChild) {
		uni.navigateTo({
			url: itemChild.url,
			success:() => {
				setStore.setMenuClicks(userStore.user.userId, userStore.roleId, itemChild.parent.name, itemChild.name)
			},
			fail: (e) => {
				if (e.errMsg.indexOf('not found') > -1) {
					uni.navigateTo({
						url: `/pages/common/webview/index?pageUrl=${pageUrl}&title=${itemChild.meta.title}`
					})
				}
			}
		})
	}
	const showMap = () => {
		uni.navigateTo({
			url: `/pages/common/webview/map`
		})
	}
	
	// 预计薪资
	const salaryMoney = computed(() => {
		let money = 0
		if (userStore?.userKpiPosts?.[0]) {
			money = userStore.userKpiPosts[0].basePay + userStore.userKpiPosts[0].performance * (kpiPercentage.value / 100)
		}
		return money
	})
	
	onMounted(() => {
		// getUser()
		if (checkPermi(['zhouyz:kpiPostSchedule:list'])) {
			getKpiPostSchedule()
		}
	})
	onPullDownRefresh(() => {
		getLocation()
		if (checkPermi(['zhouyz:kpiPostSchedule:list'])) {
			getKpiPostSchedule()
		}
		userStore.getInfo()
		userStore.getUserProfile()
		uni.stopPullDownRefresh()
	})
	onReady(() => {
		// checkUpdate()
	})
</script>

<style scoped lang="scss">
	.detail {
		padding-top: var(--status-bar-height);
		&-text {
			width: 50%;
			margin-top: 10rpx;
		}
	}
	.qiun {
		&-item {
			width: 400rpx;
			height: 400rpx;
			margin: 0 auto;
		}
	}
	.percentage {
		color: #19be6b;
	}
	
	.location {
		&-loading {
			position: relative;
			width: 200rpx;
			height: 200rpx;
			justify-content: center;
			border-radius: 50%;
			background-color: #3c9cff;
			box-shadow: 0 4px 8px rgba(60, 156, 255, 0.5);
			overflow: hidden;
			z-index: 2;
			margin: 0 auto;
			&-icon {
				position: absolute;
				width: 200rpx;
				height: 200rpx;
				top: 100rpx;
				left: 100rpx;
				background: linear-gradient(45deg, #FFFFFF, transparent 50%);
				animation: rotate 3s linear infinite;
				transform-origin: left top;
			}
			&-text {
				font-size: 36rpx;
				font-weight: bold;
				color: #FFFFFF;
			}
			&-clock {
				width: 100%;
				height: 100%;
				font-size: 36rpx;
				font-weight: bold;
				color: #FFFFFF;
				justify-content: center;
			}
		}
		&-info {
			margin-top: 40rpx;
		}
	}
	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}
		to {
			transform: rotate(360deg);
		}
	}
	.text {
	  text-align: center;
	  font-size: 26rpx;
	  margin-top: 10rpx;
	}
	.grid-list {
		align-items: flex-start;
		flex-wrap: wrap;
	}
	
	.grid-item-box {
	  flex: 1;
	  /* #ifndef APP-NVUE */
	  display: flex;
	  /* #endif */
	  flex-direction: column;
	  align-items: center;
	  justify-content: flex-start;
	  padding: 15px 0;
	}
	
	.grid-item-icon {
		width: 50rpx;
		height: 50rpx;
	}
	
	.uni-margin-wrap {
	  width: 690rpx;
	  width: 100%;
	  ;
	}
	
	.swiper {
	  height: 300rpx;
	}
	
	.swiper-box {
	  height: 150px;
	}
	
	.swiper-item {
	  /* #ifndef APP-NVUE */
	  display: flex;
	  /* #endif */
	  flex-direction: column;
	  justify-content: center;
	  align-items: center;
	  color: #fff;
	  height: 300rpx;
	  line-height: 300rpx;
	}
	
	@media screen and (min-width: 500px) {
	  .uni-swiper-dot-box {
	    width: 400px;
	    /* #ifndef APP-NVUE */
	    margin: 0 auto;
	    /* #endif */
	    margin-top: 8px;
	  }
	
	  .image {
	    width: 100%;
	  }
	}
	.charts-box {
		width: 100%;
		height: 300px;
	}
	.jf {
		justify-content: center;
		&-icon {
			width: 32px;
			height: 32px;
			margin-right: 10px;
		}
	}
</style>
